'use strict';

function urlEncode(url)
{
    if (navigator.userAgent.match(/(OS\s*(\d+))/g)) 
	{
	   return escape(url);
	}else{
	   return url;
	}
}

proxy : function(datajs, callback, url, method) {
    location.href = "hsbc://"+urlEncode("function=Proxy&datajs=" + datajs + "&callbackjs=" + callback + "&url=" + url + "&method=" + method);
}

GSPProxy : function(datajs, callback, url, method, header){
    location.href = "hsbc://"+urlEncode("function=GSPProxy&datajs=" + datajs + "&callbackjs=" + callback + "&url=" + url + "&method=" + method + "&headers=" + header);
}

proxyJSON : function(datajs, callback, url, method){
    location.href = "hsbc://"+urlEncode("function=ProxyJSON&datajs=" + datajs + "&callbackjs=" + callback + "&url=" + url + "&method=" + method);
}

iCore.prototype.hookRequire = function(name,args,callback){
	if(!$.isArray(args)) return;
	var self = this, topic = Lang.topics['9c9eb9ae133cb5b9'];
	if(topic && callback && $.isFunction(callback)){
		topic.empty();
		topic.subscribe(callback);
	}
	console.log("HookRequire:"+name);
	iMobile.app[name].apply(self,args);
}

iMobile.callBackHandler = function(data, statusCode){
    //Change for FP8 end
        var topic = Lang.topics['9c9eb9ae133cb5b9'];
        if(topic){
            var self = topic.delegate,adapt = topic.adapt, type = topic.type, name = topic.name;
            var hideLoadingFlag=topic.hideLoadingFlag;
            delete topic.adapt;
            delete topic.type;
            delete topic.name;
            delete topic.hideLoadingFlag;
            if(type == "NativeProxy"){
                self._analyse.apply(self,[data,adapt,function(result){	
                    if(hideLoadingFlag==true)
                    {
                     self.hideLoadingMask();
                  }
                    self._messageHandler.apply(self,[name,topic.get().apply(self,[result]),result]);
                }]);			
            }
            else if(type == "JsonpProxy"){
                self._jsonpAnalyse.apply(self,[data,adapt,function(result){	
                    if(hideLoadingFlag==true)
                    {
                     self.hideLoadingMask();
                  }
                    self._jsonpMessageHandler.apply(self,[name,topic.get().apply(self,[result]),result]);
                }]);			
            }
            // Add for FP8 start
            else if(type == "GSPProxy"){
                self._analyseForGSP.apply(self,[data,adapt,statusCode,function(result){
                    if(hideLoadingFlag==true){
                        self.hideLoadingMask();
                    }
                    self._messageHandlerForGSP.apply(self,[name,topic.get().apply(self,[result]),result]);
                }]);
            }
            // Add for FP8 end
            else{
                topic.publishWith(self,[data]);
                if(hideLoadingFlag==true)
                {
                 self.hideLoadingMask();
              }		
            }
        }
    }

    iFunction.prototype._analyse = function(data,adapt,execute){
	
        var rs = {valid : false, errorCode : false, errorMsg : "", data : data},self = this;
        if(!data){
            rs.errorCode = "jsonErr";
            rs.data = {};
            rs.errorMsg = self._err[rs.errorCode];
            execute(rs);
            return;
        }
        if(typeof data === "string"){
            try{
                data = $.parseJSON(data);
                rs.data = data;
                //rs.valid = true;
            }catch(err){
                var aStart = data.indexOf('<json>'), aEnd = data.indexOf('</json>');
                if(aStart > -1 && aEnd > -1){
                    var aspectJSON = data.substring(aStart + 6, aEnd);
                    try{
                        data = $.parseJSON(aspectJSON);
                        rs.data = data;
                        //rs.valid = true;					
                    }catch(e){
                        rs.errorCode = "noService";
                        rs.errorMsg = self._err[rs.errorCode];
                        execute(rs); return;
                    }
                }else{
                    rs.errorCode = "jsonErr"; rs.errorMsg = self._err[rs.errorCode];  execute(rs); return;
                }
            }
        }
        
        if(typeof rs.data === "object"){
            if(rs.data==null)
            {
                rs.errorCode = "jsonErr"; rs.errorMsg = self._err[rs.errorCode];  execute(rs); return;
            }
            if(!rs.data.hasOwnProperty('header')){
                rs.errorCode = 'headerErr';
            }else if(!rs.data.header.hasOwnProperty('statusCode')){
                rs.errorCode = 'statusCodeErr';
            }
            if(rs.errorCode !== false){
                rs.errorMsg = self._err[rs.errorCode];
                execute(rs);
                return;
            }
            
            //json schema
            require([adapt],function(adapt){
                if(data.header.statusCode == '0000'){
                    var schema = iMobile.adaptRegister(data,{"type":"object","properties" : adapt});
                    if(schema.valid && schema.errors.length == 0){
                        rs.valid = true;
                    }else{
                        rs.errorCode = 'adaptErr';
                        for(var i = 0, l = schema.errors.length; i < l; i++){
                            
                            if(self.configuration.settings.isEnableJsonLog){
                                rs.errorMsg += schema.errors[i].property + ":" + schema.errors[i].message + "<br/>";
                            }else{
                                //Mass error message.
                                rs.errorMsg += schema.errors[i].message + "<br/>";
                            }
                            
                        }				
                    }
                } else if (data.header.statusCode == 'W000') {
                    // Add handling for multiple request. W000: transaction is pending for another request while current response is valid.
                    // Skip JSON schema validation for 'W000' status as no further extraction of this response should be performed.
                    rs.valid = ture;
                }
                // Add handling for multiple request. W000: transaction is pending for another request while current response is valid.
                if(data.header.statusCode != '0000' && data.header.statusCode != 'W000'){
                        rs.valid = false;
                        rs.errorCode = data.header.statusCode;
                        rs.errorMsg = data.header.errorMsg;
                }
                execute(rs);				
            });		
        }else{
            rs.errorCode = "jsonErr";
            rs.data = {};
            rs.errorMsg = self._err[rs.errorCode];  
            execute(rs); 
            return;		
        }		
    }

    iFunction.prototype._messageHandler = function(name,handler,rs){
	
        //update the data model begin
        iData.add(name,rs.data);
        var tempHandler=handler;
        
        //end
        var self = this;
        if(rs.valid){
            $(".warningWrapper").addClass("hidden");
            handler.success.apply(self,[rs]);
            runTrackWebtrendsWithApplicationRequest(name, true, rs);
            return;
        }
        if(handler.error && $.isFunction(handler.error) && rs.errorCode != "S003"){
            var rsData=rs.data;
            if(rsData!=undefined && rsData!='' && rsData.hasOwnProperty('header'))
            {
              handler.error.apply(self,[rs]);
          }
        }
        var errorConfig = this.apis[name]['err'], statusCode = rs.errorCode, error = rs.errorMsg, errorCode = [], errorMsg = [], target = "errorWrapper", handler=null, err,warningWrapper=null,animation=null,isShowCancel=null;
        /*dcd multiple logon fix*/
        var dcsuri = $(self.currentViewController.view.layer).find("div[role=headbar]").attr('dcsuri');
        /*dcd multiple logon fix */
        if($.isArray(error)){
            errorCode[0] = statusCode;
            errorMsg[0] = self._err[statusCode]||"";		
            for(var i = 0, l = error.length; i<l; i++){
                errorCode[i] = error[i].code;
                /* implement for SOTP and mobile 1.5 [start] */
                if(i==0 && error[i].desc.indexOf(self._err['delimiter']) > 0){
                    // divide the desc string into title and msg
                    var errMsgArr = error[i].desc.split(self._err['delimiter']);
                    if(errMsgArr[0] != null && errMsgArr[0]!=''){
                        error[i].desc = '<span style="font-weight:bold;padding-bottom:3px;display:block;">' + errMsgArr[0] + '</span>' + errMsgArr[1];
                    }
                }
                /* implement for SOTP and mobile 1.5 [end] */
                errorMsg[i] = error[i].desc||self._err[statusCode]||"";
            }
        }else if(Lang.isString(error)){
            //no error code, use statusCode
            errorCode[0] = statusCode;
            /* implement for SOTP and mobile 1.5 [start] */
            if(error.indexOf(self._err['delimiter']) > 0){
                // divide the desc string into title and msg
                var errMsgArr = error.split(self._err['delimiter']);
                if(errMsgArr[0] != null && errMsgArr[0]!=''){
                    error = '<span style="font-weight:bold;padding-bottom:3px;display:block;">' + errMsgArr[0] + '</span>' + errMsgArr[1];
                }
            }
            /* implement for SOTP and mobile 1.5 [end] */
            errorMsg[0] = error;
        }else if(error==undefined){
             errorCode[0] = statusCode;
             errorMsg[0] = self._err[statusCode]||"";
        }
        
        
        if(errorCode.length > 1){
            errorCode =  errorCode[0];
            errorMsg = errorMsg.join("<br/>");
        }else if(errorCode.length == 1){
            errorCode = errorCode[0];
            errorMsg = errorMsg[0];
        }
        if(errorCode!=undefined&&errorCode!=""){
            if(errorCode !== statusCode){
                for(err in errorConfig){
                    if(err.indexOf(statusCode) > -1){
                        target = errorConfig[err].target || target;
                      handler = errorConfig[err].handler;
                      warningWrapper= errorConfig[err].warningWrapper;	
                      animation=errorConfig[err].animation;	
                      isShowCancel=errorConfig[err].isShowCancel;	
                        for(var e in errorConfig[err]){
                            if(e.indexOf(errorCode) > -1){
                                target = errorConfig[err][e].target || target;
                                handler = errorConfig[err][e].handler|| handler;
                                warningWrapper= errorConfig[err][e].warningWrapper|| warningWrapper;
                                animation= errorConfig[err][e].animation|| animation;
                                var tempIsShowCancel= errorConfig[err][e].isShowCancel;
                                    if(tempIsShowCancel!=undefined){
                                    isShowCancel=tempIsShowCancel;
                                }
                                isShowCancel= errorConfig[err][e].isShowCancel|| isShowCancel;
                                matchErrCode=true;
                                break;
                            }
                        }
                        break;
                    }
                }		
            }else{
                for(err in errorConfig){
                    if(err.indexOf(errorCode) > -1){
                        target = errorConfig[err].target || target;
                        handler = errorConfig[err].handler;
                        warningWrapper= errorConfig[err].warningWrapper;
                        animation= errorConfig[err].animation;
                        isShowCancel= errorConfig[err].isShowCancel;
                        break;
                    }
                }
            }
        }
        //Multiple logon error handle
        if(statusCode=="C006" || statusCode=="C012")
        {
         errorMsg=self._err[statusCode];
        }
        if(statusCode=="C001"){
            if(self.configuration.settings.securityType === "SaaS"){
                var lastReqForTimeout = iData.get("lastReq"), url = (lastReqForTimeout.url || (self.configuration.settings.host + self.apis[lastReqForTimeout.name].url));
                  
                if(!self.saasTimeout){   	//load timeout.js
                    require(["SaaS/timeout"], function(SaaSTimeout){
                        self.saasTimeout = new SaaSTimeout(self);  
                           //call the api from timeout to check, pass the last request for handling
                        self.saasTimeout.checkTimeout(rs.data.body, self.locale, function(){
                            self.request(lastReqForTimeout);   //re-send previous request
                        });
                      });
                }else{
                      //call the api from timeout to check, pass the last request for handling
                      self.saasTimeout.checkTimeout(rs.data.body, self.locale, function(){
                          self.request(lastReqForTimeout);   //re-send previous request
                      });
                  }
                runTrackWebtrendsWithApplicationRequest(name, false, rs);
                  return;
            }else if(self.configuration.settings.securityType === "Legacy"){
                self._isTimeout=true;
            }	   
      }
        this._multipleLogonError = false;
        /*Fix defect #1017*/
        if((errorCode!=undefined && errorCode!='' && ((errorCode.indexOf('0014')!=-1 && statusCode=="C000")|| (statusCode=="C006") )) || (errorMsg.indexOf("8010")!= -1 && dcsuri.indexOf("dcd") != -1 && statusCode == "E000"))
        {
            this._multipleLogonError = true;
        }
        /*Fix defect 50*/
        var multipleLogonErrorCall = function(){
            /*dcd multiple logon fix*/
            if((errorCode!=undefined && errorCode!='' && ((errorCode.indexOf('0014')!=-1 && statusCode=="C000")|| (statusCode=="C006") )) || (errorMsg.indexOf("8010")!= -1 && dcsuri.indexOf("dcd") != -1 && statusCode == "E000"))
            {
                //fix multiple logon error - start - 14Oct2013
                self.request({name : 'timeoutLogoff',adaptorPath:self.configuration.settings.authConfigPath, method : 'post', data : self.timeoutLogoffData});
                //fix multiple logon error - end - 14Oct2013
            }
        }
        this._commonError = false;
        this._backToApp=false;
        
        if(self.configuration.settings.error_back_mapping[statusCode] && !handler && target != "goToSuccess" && target != "handleByPage" && target != "warning"){
            target = "commonError";
        }	
        //check out if it is a common error or not
        if(target === 'commonError'){
            //hide back button in errorView
            /*dcd multiple logon fix*/
            if(self.configuration.settings.error_back_mapping[statusCode]=='backToApp' ||(errorMsg.indexOf("8010")!= -1 && dcsuri.indexOf("dcd") != -1 && statusCode == "E000"))
            {
                this._backToApp=true;
                target = 'errorWrapper';
              $("a.errorBtnOK",this.errorViewController.view.layer).removeClass('hidden');
              $("a.errorBtnCancel",this.errorViewController.view.layer).addClass('hidden');
              $("a.errorBtnBack",this.errorViewController.view.layer).addClass('hidden');
            }else{
                $('div.error-panel>p',self.commonErroViewController.view.layer).html(errorMsg||self._err['noService']);
            }
            this._commonError = true;
        }
        else{
            if(!handler || !Lang.isFunction(self[handler])){
                handler = self.configuration.settings.error_back_mapping[statusCode]||"goBack";
            }
            this._handler = handler;
            if(isShowCancel==true){
                $("a.errorBtnCancel",this.errorViewController.view.layer).removeClass('hidden');
                $("a.errorBtnBack",this.errorViewController.view.layer).addClass('hidden');
                $("a.errorBtnOK",this.errorViewController.view.layer).addClass('hidden');
            }else if(isShowCancel=="OK") {
              $("a.errorBtnOK",this.errorViewController.view.layer).removeClass('hidden');
              $("a.errorBtnCancel",this.errorViewController.view.layer).addClass('hidden');
              $("a.errorBtnBack",this.errorViewController.view.layer).addClass('hidden');
            }else{
              $("a.errorBtnOK",this.errorViewController.view.layer).addClass('hidden');
              $("a.errorBtnCancel",this.errorViewController.view.layer).addClass('hidden');
              $("a.errorBtnBack",this.errorViewController.view.layer).removeClass('hidden');
            }
        }
        //if errorMsg is null then show noService msg
        /*dcd multiple logon fix*/
        if(errorMsg.indexOf("8010")!= -1 && dcsuri.indexOf("dcd") != -1 && statusCode == "E000"){
            errorMsg = self._err["C006"];
        }
        /*dcd multiple logon fix*/
        $('div.error-panel>p',self.errorViewController.view.layer).html(errorMsg||self._err['noService']);
        if(target != undefined && target == "goToSuccess")
        {
            if(warningWrapper!= undefined)
            {
                $("#"+warningWrapper).addClass("error-content").find("div:first").removeClass("hidden").html(errorMsg);
                $("#"+warningWrapper).removeClass("hidden");
          }
            tempHandler.success.apply(self,[rs]);
            runTrackWebtrendsWithApplicationRequest(name,true, rs);
            return;
        }
        runTrackWebtrendsWithApplicationRequest(name,false,rs);
        //step up
        if(statusCode=="C003")
        {
            if(self.configuration.settings.securityType == "SaaS"){
                var lastReqForStepup = iData.get("lastReq"), url = (lastReqForStepup.url || (self.apis[lastReqForStepup.name].url));
                //saas mock for testing.
                console.log("SaaS:last reqeust url is - "+url);
                  
                if(!self.saasStepup){   	//load stepup.js
                    require(["SaaS/stepup"], function(SaaSStepup){
                        self.saasStepup = new SaaSStepup(self);  
                           //call the api from stepup to check, pass the last request for handling
                        self.saasStepup.requestStepup(rs.data.body, self.locale, function(){
                            //add for saas mock testing , need to remove later
                            self.request(lastReqForStepup);   //re-send previous request
                        });
                      });
                }else{
                      //call the api from stepup to check, pass the last request for handling
                      self.saasStepup.requestStepup(rs.data.body, self.locale, function(){
                      //add for saas mock testing , need to remove later
                            self.request(lastReqForStepup);   //re-send previous request
                      });
                  }
                self.getStepupContentPage();
                  return;
            }else if(self.configuration.settings.securityType == "Legacy"){
                iData.add("reqBeforeStepUp",iData.get('lastReq'));
                self.goTo("stepUp","fade");
                self.getStepupContentPage();
                return;
            }
        }
        else if(statusCode=="C002" )
        {
             self.request({name : 'reAuthCheck',adaptorPath:self.configuration.settings.authConfigPath, method : 'post', data : self.reauthCheckSubmitData,callback : self.reauthCheckCallBack });
         return;
        }else if(statusCode=="C012" && self.configuration.settings.isHTMLSupportSOTP && self._isAppSupportSOTP == 'true'&& self.configuration.settings.securityType != 'SaaS'){/* implement for SOTP [start] */
            self.goTo("insuffCredential","fade");
            return;
            }
            /* implement for SOTP [end] */
        else if(target != "warning" && target != "handleByPage")
        {
             if(this._commonError==true)
             {
                  self.goTo(target,"slideup");
                  multipleLogonErrorCall();
             }
             else
             {
                  if(animation!=undefined && animation!=null && animation!='')
                  {
                     self.goTo(target,animation);
                     multipleLogonErrorCall();
                  }else{
                     self.goTo(target);
                     multipleLogonErrorCall();
                  }
             }
        }
        if(statusCode == "S001"){
            logon.prototype.showPageFromLoading('logon_migrationInfo',0);
        }	 
    }

    logon.prototype.cs_handleOldSaaSError = function(callback) {
        var self = this;
        if (callback.hasOwnProperty('saasErrorMsg')) {
            if (callback.errorCode.match(/E001|E000/) && callback.saasErrorMsg != '') {
                if (callback.saasErrorMsg.indexOf("@@@") <= -1) {
                    callback.saasErrorMsg = "System Error@@@" + callback.saasErrorMsg;
                }
                self.cs_SystemError(null, callback.saasErrorMsg.replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
                self.handleJsonError4SOTP(callback);
                return;
            }
        }
    }

    if (self._csSaaSProfile.responseInfo.reasons.length > 0) {
		
		if (self._camType == "CAM30") {
			
			if (self._csSaaSProfile.isPwdLocked) {
				self._csSaaSProfile.err.isSuccess = false;
				if (!self._csSaaSProfile.isOtpTempLock && !self._csSaaSProfile.isOTPLocked) {
					iData.get('cs_pwdLockCTA_cam40').removeClass("hidden");
				}
				iData.get('cs_secKeyCTA_cam30').addClass("hidden");
				$(".cs_LinkArea").addClass("hidden");
				$(".dividerLine").addClass("hidden");
				if (self._csSaaSProfile.isPasswordAuthAllowed && !self._csSaaSProfile.isOTPAuthAllowed) {
					iData.get('cs_secKeyCTA_cam30').addClass("hidden");
					iData.get('cs_pwdLockCTA_cam40').addClass("hidden");
					iData.get('cs_customerHelpCTA').addClass("hidden");
					iData.get('cs_pwdRecoveryCTA').removeClass("hidden");
					
					self.cs_SystemError(null, self.saasErr["cs_passwordOnlyLockedErr"].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
				} else {
					iData.get('cs_secKeyCTA_cam30').addClass("hidden");
					iData.get('cs_pwdLockCTA_cam40').removeClass("hidden");
					iData.get('cs_customerHelpCTA').addClass("hidden");
					iData.get('cs_pwdRecoveryCTA').removeClass("hidden");
					self.cs_SystemError(null, self.saasErr["cs_passwordLockedErr"].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
				}
			} else if (self._csSaaSProfile.isPwdTempLock || self._csSaaSProfile.pwdDosiRemainAttempt != null && Number(self._csSaaSProfile.pwdDosiRemainAttempt) <= 0) {
				console.log("The profile pwdDosiRemainAttempt is 0 now.");
				self._csSaaSProfile.err.isSuccess = false;
				self._backType4SOTP = 'backToApp';
				if (!self._csSaaSProfile.isOtpTempLock && !self._csSaaSProfile.isOTPLocked) {
					iData.get('cs_pwdLockCTA_cam40').removeClass("hidden");
				}
				$(".cs_LinkArea").addClass("hidden");
				$(".dividerLine").addClass("hidden");
				
				if (self._csSaaSProfile.isPasswordAuthAllowed && !self._csSaaSProfile.isOTPAuthAllowed) {
					iData.get('cs_secKeyCTA_cam30').addClass("hidden");
					iData.get('cs_pwdLockCTA_cam40').addClass("hidden");
					iData.get('cs_customerHelpCTA').addClass("hidden");
					iData.get('cs_pwdRecoveryCTA').addClass("hidden");//fix defect #59574
					self.cs_SystemError(null, self.saasErr['cs_passwordOnlyTempLockedErr'].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
					
				} else {
					
					iData.get('cs_secKeyCTA_cam30').addClass("hidden");
					iData.get('cs_pwdLockCTA_cam40').removeClass("hidden");
					iData.get('cs_customerHelpCTA').addClass("hidden");
					iData.get('cs_pwdRecoveryCTA').addClass("hidden");
					
					self.cs_SystemError(null, self.saasErr['cs_passwordTempLockedErr'].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
				}
			} else if (self._csSaaSProfile.isPwdRequireDosi && self._csSaaSProfile.pwdDosiRemainAttempt != null
				 && Number(self._csSaaSProfile.pwdDosiRemainAttempt) < 3 && Number(self._csSaaSProfile.pwdDosiRemainAttempt) > 0) {
				self._csSaaSProfile.err.isSuccess = false;
				if ($('#cs_pwdDOB').hasClass("hidden")) {
					$('#cs_pwdDOB').removeClass("hidden");
					iData.get("cs_pwdDOB_error").removeClass("hidden");
					self.cs_initUsername(self.cs_getCAM30PwdObj().btn, iData.get('i18n').cs_logon_button);
					$("#cs_passwordShow").removeClass("hidden");
				} else {
					self.DOBPageErrorShow(self.cs_getCAM30PwdObj());
					$("#cs_passwordShow").removeClass("hidden");
				}
				
			} else {
				if (self._csSaaSProfile.isPwdRequireDosi != null && self._csSaaSProfile.isPwdRequireDosi && self._csSaaSProfile.pwdRemainAttempt < 3) {
					self._csSaaSProfile.err.isSuccess = false;
					self.cs_initUsername(self.cs_getCAM30PwdObj().btn, iData.get('i18n').cs_logon_button);
					iData.get("cs_pwdDOB_error").removeClass("hidden");
					$('#cs_pwdDOB').removeClass("hidden");
					$("#cs_passwordShow").removeClass("hidden");
					$(".cs_sp_placeholder").addClass("hidden");
				} else if (self._csSaaSProfile.responseInfo.reasons[0].traceCde[0].cde === 'USR_PWA_VAL_105') {
					$("#cs_passwordShow").removeClass("hidden");
					$(".cs_sp_placeholder").addClass("hidden");
					self.cs_WarningShow(self.cs_getCAM30PwdObj(), null, self._csSaaSProfile.err.errMsg.replace(/~~1/, self._csSaaSProfile.pwdRemainAttempt));
					return;
				}
				
			}
			
		} else if (self._camType == "CAM40") {
			
			if (self._csSaaSProfile.isOTPLocked) {
				self._csSaaSProfile.err.isSuccess = false;
				//if (!self._csSaaSProfile.isPwdTempLock && !self._csSaaSProfile.isPwdLocked) {
				iData.get('cs_secKeyCTA_cam30').removeClass("hidden");
				//}
				iData.get('cs_pwdRecoveryCTA').addClass("hidden");// fix AU defect 95337
				iData.get('cs_pwdLockCTA_cam40').addClass("hidden");
				$(".cs_LinkArea").addClass("hidden");
				$(".dividerLine").addClass("hidden");
				iData.get('cs_pwdRecoveryCTA').addClass("hidden");// fix US defect 87670
				self.cs_SystemError(null, self.saasErr['cs_secureKeyLockedErr'].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
				//iData.get('cs_customerHelpCTA').removeClass("hidden"); //Gavin fix defect #59968
			} else if (self._csSaaSProfile.isOtpRequireDosi && self._csSaaSProfile.otpDosiRemainAttempt != null
				 && Number(self._csSaaSProfile.otpDosiRemainAttempt) < 3 && Number(self._csSaaSProfile.otpDosiRemainAttempt) > 0) {
				self._csSaaSProfile.err.isSuccess = false;
				if ($('#cs_otpDOB').hasClass("hidden")) {
					$('#cs_otpDOB').removeClass("hidden");
					iData.get("cs_otpDOB_error").removeClass("hidden");
					self.cs_initUsername(self.cs_getOTPAuthObj().btn, iData.get('i18n').cs_logon_button);
				} else {
					self.DOBPageErrorShow(self.cs_getOTPAuthObj());
				}
				
			} else if (self._csSaaSProfile.isOtpTempLock || self._csSaaSProfile.otpDosiRemainAttempt != null && Number(self._csSaaSProfile.otpDosiRemainAttempt) <= 0) {
				console.log("The profile otpDosiRemainAttempt is 0 now.");
				self._csSaaSProfile.err.isSuccess = false;
				self._backType4SOTP = 'backToApp';
				if (!self._csSaaSProfile.isPwdTempLock && !self._csSaaSProfile.isPwdLocked) {
					iData.get('cs_secKeyCTA_cam30').removeClass("hidden");
				}
				$(".cs_LinkArea").addClass("hidden");
				$(".dividerLine").addClass("hidden");
				
				iData.get('cs_secKeyCTA_cam30').removeClass("hidden");
				iData.get('cs_pwdLockCTA_cam40').addClass("hidden");
				iData.get('cs_customerHelpCTA').addClass("hidden");
				iData.get('cs_pwdRecoveryCTA').addClass("hidden");
				self.cs_SystemError(null, self.saasErr['cs_secureKeyTempLockedErr'].replace(/~~1/, self.configuration.settings.SOTP.callCenter).replace(/~~2/, self.configuration.settings.SOTP.callCenterTime));
				
			} else {
				if (self._csSaaSProfile.isOtpRequireDosi != null && self._csSaaSProfile.isOtpRequireDosi) {
					self._csSaaSProfile.err.isSuccess = false;
					iData.get("cs_otpDOB_error").removeClass("hidden");
					$('#cs_otpDOB').removeClass("hidden");
					self.cs_initUsername(self.cs_getOTPAuthObj().btn, iData.get('i18n').cs_logon_button);
				} else if (self._csSaaSProfile.responseInfo.reasons[0].traceCde[0].cde.match(/USR_OTA_VAL_100|USR_OTA_VAL_106/)) {
					self.cs_WarningShow(self.cs_getOTPAuthObj(), null, self._csSaaSProfile.err.errMsg.replace(/~~1/, self._csSaaSProfile.otpRemainAttempt));
					return;
				}
				
			}
			
		}
		
	} else { // Target to handle E000, E001;
		self.cs_SystemError(callback, "");
	}